package com.lxs.doc.rocess.common;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class AdvancedDocOutlineParser {
    public static List<OutlineItem> extractOutlineHierarchy(String filePath) {
        List<OutlineItem> outline = new ArrayList<>();

        try (FileInputStream fis = new FileInputStream(filePath);
             HWPFDocument document = new HWPFDocument(fis)) {

            Range range = document.getRange();
            Stack<OutlineItem> stack = new Stack<>();

            for (int i = 0; i < range.numParagraphs(); i++) {
                Paragraph paragraph = range.getParagraph(i);
                String text = paragraph.text().trim();

                if (text.isEmpty()) continue;

                int level = paragraph.getLvl();
                OutlineItem item = new OutlineItem(
                        i, text, level, paragraph.getStyleIndex()
                );

                // 构建层次结构
                while (!stack.isEmpty() && stack.peek().level >= level) {
                    stack.pop();
                }

                if (!stack.isEmpty()) {
                    stack.peek().addChild(item);
                } else {
                    outline.add(item);
                }

                stack.push(item);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return outline;
    }

    // 大纲项类
    public static class OutlineItem {
        int index;
        String text;
        int level;
        int styleIndex;
        List<OutlineItem> children;

        public OutlineItem(int index, String text, int level, int styleIndex) {
            this.index = index;
            this.text = text;
            this.level = level;
            this.styleIndex = styleIndex;
            this.children = new ArrayList<>();
        }

        public void addChild(OutlineItem child) {
            children.add(child);
        }

        public void print(String indent) {
            System.out.printf("%s[%d] L%d: %s%n",
                    indent, index, level, text);
            for (OutlineItem child : children) {
                child.print(indent + "  ");
            }
        }
    }
}
